/*
 * Anything: A flexible and easy to use data structure that combines the 
 * characteristics of a list and a hashmap into one data structure.
 * 
 * Based on a paper by Peter Sommerlad and Marcel Rueedi on 
 * 'Do-it-yourself reflection' entered at EuroPLOP 1998.
 * 
 * This library was written completely from scratch and is based only 
 * in spirit on the original Java Anything implementation written by 
 * Andre Weinand/Marcel Rueedi in 1997/99 and enhanced by Stefan Tramm 
 * in 2006.
 * 
 * Copyright (c) 2008 Thomas Marti and others. All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package any.impl;


import static java.lang.String.format;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;

import any.Any;
import any.impl.util.Base64Codec;
import any.impl.util.StringEscapeUtils;


final class StringAnything extends SimpleTypeAnything<String> {

	private static final long serialVersionUID = 1;

	private static final String QUOTED_STRING = "\"%s\"";
	
	StringAnything(CharSequence contents) {
		super(contents.toString());
	}
	
	public Any toAny() {
		return new StringAnything(contents);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T toNative() {
		//TODO: null wenn "*", UnknownObject, etc...??
		Object value = asBigDecimalImpl();
		if (value != null) {
			return (T)value;
		} 
		
		value = asDouble(null);		
		if (value != null) {
			return (T)value;
		} 
		
		value = asBool(null);
		if (value != null) {
			return (T)value;
		}

		value = asDate(null);
		if (value != null) {
			return (T)value;
		}

		value = asSerializable();
		if (value != null) {
			return (T)value;
		}

		return (T)contents;			
	}
	
	private Object asSerializable() {
		try {
			byte[] bytes = Base64Codec.decode(contents);
			return new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject();
		} catch (Exception e) {
			return null;
		}
	}

	public Boolean asBool(Boolean defaultValue) {
		String trimmed = contents.trim();
		if (trimmed.equalsIgnoreCase("true")) {
			return Boolean.TRUE;
		} else if (trimmed.equalsIgnoreCase("false")) {
			return Boolean.FALSE;
		} else {
			return defaultValue;
		}
	}

	@Override
	public Double asDoubleImpl(Number defaultValue) {
		String formatted = contents
		                   .trim()
		                   .replaceFirst("[Nn][Aa][Nn]", "NaN")
		                   .replaceFirst("[Ii][Nn][Ff][Ii][Nn][Ii][Tt][Yy]", "Infinity")
		                   ;
		try {
			return Double.valueOf(formatted);
		} catch (NumberFormatException e) {}
		
		return null;
	}

	@Override
	public BigDecimal asBigDecimalImpl() {
		try {
			return new BigDecimal(contents.trim());
		} catch (NumberFormatException e) {}
		
		return null;
	}
	
	public Date asDate(Date defaultValue) {
		for (int i = 0; i < ANY_DATE_FORMATS.length; i++) {
			try {
				return ANY_DATE_FORMATS[i].parse(contents);
			} catch (ParseException e) {}
		}
		
		return defaultValue;
	}
	
	@Override
	public String toString() {
		return format(QUOTED_STRING, StringEscapeUtils.escapeJava(contents));

//		if (escapeString(contents).matches(".*\\s.*")) {
//			return format(QUOTED_STRING, StringEscapeUtils.escapeJava(contents));
//		} else {
//			return contents;
//		}
	}
	
	@Override
	public String toFullString() {
		return "String\"" + escapeString(contents) + "\"";
	}
	
	private static String escapeString(String str) {
		if (str == null || str.length() == 0) {
			return str;
		}
		
		StringBuilder result = new StringBuilder(str.length());
		for (int i = 0; i < str.length(); i++) {
			char nextChar = str.charAt(i);
			if (Character.isWhitespace(nextChar)) {
				result.append(format("%c", nextChar));				
			} else {
				result.append(nextChar);
			}
		}
		
		return result.toString();
	}
	
}
